package com.dunqi.gpm.cangxi.home.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.util.CommonUtil;
import com.dunqi.gpm.cangxi.common.view.ComTitleBar;
import com.dunqi.gpm.cangxi.home.bean.IndexList;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;


public class VideoActivity extends AppCompatActivity {

    private VideoView videoView;
    private TextView percentTv;
    private TextView netSpeedTv;

    private static final String URLS = "url";
    private ComTitleBar titleBar;
    String videoUrl;
    private View stateView;
    private View progressBar;
    private View backIv;
    private View changeStreamTv;
    private TextView steamTv;
    private ArrayList<IndexList> urls;
    int index = 0;
    private String desUrlText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_video2);


        initUiAndListener();
    }

    protected void initUiAndListener() {
        Intent intent = getIntent();
        if (intent != null) {
            urls = (ArrayList<IndexList>) intent.getSerializableExtra(URLS);

        }


        //显示缓冲百分比的TextView
        percentTv = (TextView) findViewById(R.id.buffer_percent);
        //显示下载网速的TextView
        netSpeedTv = (TextView) findViewById(R.id.net_speed);
        //初始化加载库文件

        progressBar = findViewById(R.id.progress_bar);

        stateView = findViewById(R.id.state_view);

        backIv = findViewById(R.id.back_iv2);
        changeStreamTv = findViewById(R.id.change_stream_tv);

        steamTv = findViewById(R.id.stream_tv);

        videoUrl = urls.get(index).getHlsIndex();
        desUrlText = urls.get(index).getResolution();

        steamTv.setText(desUrlText);

        initStateView();


        init();

        titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle("会议室");


        changeStreamTv.setOnClickListener(new ChangeSteamListener());
        titleBar.setOnClickListenerOfRight(new ChangeSteamListener());

        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }


    class ChangeSteamListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (urls == null) {
                return;
            }
            index++;
            IndexList indexList;
            try {
                indexList = urls.get(index);
            } catch (Exception e) {
                index = 0;
                indexList = urls.get(index);
            }
            videoUrl = indexList.getHlsIndex();
            desUrlText = indexList.getResolution();
            steamTv.setText(desUrlText);
            CommonUtil.showSingleToast(desUrlText);
            videoView.stopPlayback();
            clearVideo();
            if (TextUtils.isEmpty(videoUrl)) {
                CommonUtil.showSingleToast("播放地址为空，请尝试切换码流");
                return;
            }
            videoView.setVideoURI(Uri.parse(videoUrl));
        }
    }

    private void clearVideo() {

        videoView.getHolder().addCallback(new SurfaceHolder.Callback2() {
            @Override
            public void surfaceRedrawNeeded(SurfaceHolder holder) {


            }

            @Override
            public void surfaceCreated(final SurfaceHolder holder) {
                Observable.just(holder)
                        .observeOn(Schedulers.io())
                        .subscribe(new Consumer<SurfaceHolder>() {
                            @Override
                            public void accept(SurfaceHolder holder) throws Exception {
                                if (holder != null) {
                                    Canvas canvas = holder.lockCanvas();
                                    if (canvas != null) {
                                        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                                        holder.unlockCanvasAndPost(canvas);
                                    }
                                }
                            }
                        });
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }


    private void initStateView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            stateView.setVisibility(View.VISIBLE);
        } else {
            stateView.setVisibility(View.GONE);
        }
    }

    private void init() {
        if (Vitamio.isInitialized(this)) {
            videoView = (VideoView) findViewById(R.id.vitamio);
            if (TextUtils.isEmpty(videoUrl)) {
                CommonUtil.showSingleToast("播放地址为空，请尝试切换码流");
            }else {
                videoView.setVideoURI(Uri.parse(videoUrl));
            }
            videoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);

            final MediaController controller = new MediaController(this);
            videoView.setMediaController(controller);
            videoView.setBufferSize(10240); //设置视频缓冲大小。默认1024KB，单位byte
            videoView.requestFocus();
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    // optional need Vitamio 4.0
                    mediaPlayer.setPlaybackSpeed(1.0f);
                    //mediaPlayer.setLooping(true);
                }
            });

            videoView.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    percentTv.setText("已缓冲：" + percent + "%");
                }
            });

            videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(MediaPlayer mp, int what, int extra) {
                    switch (what) {
                        //开始缓冲
                        case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                            progressBar.setVisibility(View.VISIBLE);
                            percentTv.setVisibility(View.VISIBLE);
                            netSpeedTv.setVisibility(View.VISIBLE);
                            mp.pause();
                            break;
                        //缓冲结束
                        case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                            progressBar.setVisibility(View.GONE);
                            percentTv.setVisibility(View.GONE);
                            netSpeedTv.setVisibility(View.GONE);
                            mp.start(); //缓冲结束再播放
                            break;
                        //正在缓冲
                        case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:
                            netSpeedTv.setText("当前网速:" + extra + "kb/s");
                            break;
                    }
                    return true;
                }
            });
            controller.setOnFullClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    } else {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    }
                }
            });
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // land donothing is ok
            stateView.setVisibility(View.GONE);
            titleBar.setVisibility(View.GONE);
            backIv.setVisibility(View.VISIBLE);
            changeStreamTv.setVisibility(View.VISIBLE);

        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // port donothing is ok  竖屏
            titleBar.setVisibility(View.VISIBLE);
            backIv.setVisibility(View.GONE);
            changeStreamTv.setVisibility(View.GONE);
            initStateView();
        }

    }

    public static void start(AppCompatActivity activity, ArrayList<IndexList> list) {
        Intent intent = new Intent(activity, VideoActivity.class);
        intent.putExtra(URLS, list);
        activity.startActivity(intent);
    }

}